package com.mfw.mq;


import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.apache.rocketmq.client.core.RocketMQClientTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

@Service
public class RocketMQProducer {
    private static Logger logger = LoggerFactory.getLogger(RocketMQProducer.class);
    private String normalTopic = "test_1_topic";
    private String delayTopic = "dddii";

    @Autowired
    private RocketMQClientTemplate rocketMQClientTemplate;


    public void sendNormalMessage() {
        Message<byte[]> message = MessageBuilder.withPayload("test message=================".getBytes())
            .setHeader("TAGS", "pay_success2")  // Tag
            .setHeader("KEYS", "order_10012")   // Key
            .build();


        SendReceipt sendReceipt = rocketMQClientTemplate.syncSendNormalMessage(normalTopic, message);
        logger.info("normalSend to topic {} sendReceipt={}", normalTopic, sendReceipt);
    }


    public void sendDelayMessage() {
        SendReceipt sendReceipt;

        sendReceipt = rocketMQClientTemplate.syncSendDelayMessage(delayTopic, MessageBuilder.
            withPayload(("test message 10 " + System.currentTimeMillis()).getBytes()).build(), Duration.ofSeconds(10));
        logger.info("delaySend to topic {} sendReceipt={}", delayTopic, sendReceipt);

        sendReceipt = rocketMQClientTemplate.syncSendDelayMessage(delayTopic, "this is my message 30 " + System.currentTimeMillis(),
            Duration.ofSeconds(30));
        logger.info("delaySend to topic {} sendReceipt={}", delayTopic, sendReceipt);

        sendReceipt = rocketMQClientTemplate.syncSendDelayMessage(delayTopic, "byte messages 60".getBytes(StandardCharsets.UTF_8),
            Duration.ofSeconds(60));
        logger.info("delaySend to topic {} sendReceipt={}", delayTopic, sendReceipt);
    }

}
